package com.bawei.product.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.bawei.common.core.exception.ServiceException;
import com.bawei.common.core.utils.bean.BeanUtils;
import com.bawei.product.domain.req.*;
import com.bawei.product.domain.vo.ProductInfoVo;
import com.bawei.product.domain.vo.ProductSkuVo;
import com.bawei.product.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ProductServiceImpl implements ProductService {
    @Override
    @Transactional
    public void saveOrUpdate(ProductInfoReq productInfoReq) {

        //TODO 迭代为异步 参数校验
        checkParmas(productInfoReq);
        //TODO start
        //保存商品基本信息
        //构建表实体并赋值
        //调用mapper完成插入并获取主键id
        //TODO end
        //保存sku
        productInfoReq.setId(1l);
        saveSku(productInfoReq);
        log.debug("id：{}",productInfoReq.getId());
        //保存优惠信息表
            //保存相册表
            //保存专题


    }

    @Override
    public ProductInfoVo getProductDetailById(Long productId) {
        //构建返回结果集
        ProductInfoVo productInfoVo = new ProductInfoVo();
        //根据商品id查询商品表，获取商品基本信息
        //productInfoVo = getBaseInfoById();
        //获取优惠信息
        setOffers(productInfoVo);
        //获取sku信息
        setSkuInfos(productInfoVo);
        //获取相册
        //setImages(productInfoVo);

        return productInfoVo;
    }

    private void setSkuInfos(ProductInfoVo productInfoVo) {
        // 构建结果集
        List<ProductSkuVo> result = new ArrayList<>();

        // 查询商品的sku集合
        //List<ProductSku> skus = mapper.getSkusByPid(productInfoVo.getId());
        List<ProductSku> skus = null;
        if (skus.isEmpty()) {
            return;
        }

        // 获取skuIds
        List<Long> skuIds = skus.stream().map(ProductSku::getId).collect(Collectors.toList());

        // 查询sku属性集合
        //List<ProductSkuAttr> skuAttrs = mapper.getSkuAttrsBySkuIds(skuIds);
        List<ProductSkuAttr> skuAttrs = null;

        // 构建sku信息
        skus.forEach(productSku -> {
            ProductSkuVo productSkuVo = new ProductSkuVo();
            BeanUtils.copyProperties(productSku, productSkuVo);

            // 设置sku属性
            skuAttrs.stream()
                    .filter(productSkuAttr -> productSku.getId().equals(productSkuAttr.getSkuId()))
                    .forEach(productSkuAttr -> productSkuVo.put(productSkuAttr.getAttrId(), productSkuAttr.getAttrValueId()));

            result.add(productSkuVo);
        });
    }


    private void setOffers(ProductInfoVo productInfoVo) {
        //根据优惠type拿productId去对应的表查询优惠信息
        if (productInfoVo.getOffersType() == 1){
            //查询会员信息，
            productInfoVo.setShopLadders(null);
        }
    }

    public static void main(String[] args) {
        List<ProductSkuReq> productSkuList = null;
        productSkuList.forEach(productSkuReq -> {
            System.out.println(JSONObject.toJSONString(productSkuReq));
        });
    }

    private void saveSku(ProductInfoReq productInfoReq) {
        try {
            // 获取基本SKU信息
            List<ProductSkuReq> productSkuList = productInfoReq.getProductSkuList();
            if (productSkuList == null || productSkuList.size() == 0){
                throw new ServiceException("商品SKU不能为空");
            }

            List<ProductSku> skus = new ArrayList<>();
            List<ProductSkuAttr> attrs = new ArrayList<>();

            productSkuList.forEach(productSkuReq -> {
                // 分配商品ID
                productSkuReq.setProductId(productInfoReq.getId());

                // 从继承的map中提取属性

                ProductSku productSku = JSONObject.parseObject(JSONObject.toJSONString(productSkuReq), ProductSku.class);
                HashMap newProductSkuReq = JSONObject.parseObject(JSONObject.toJSONString(productSku), HashMap.class);
                Set skuReqKey = productSkuReq.keySet();
                Set skuKey = newProductSkuReq.keySet();

                // 去除重复项
                Set set = new HashSet<>(skuReqKey);
                set.removeAll(skuKey);

                // 为SKU设置背景图片
                productSku.setBgImg(getSkuBgImage(productSkuReq, productInfoReq.getAttrImages()));
                skus.add(productSku);

                set.forEach(key -> {
                    // 创建SKU属性
                    ProductSkuAttr productSkuAttr = new ProductSkuAttr();
                    productSkuAttr.setSkuId(productSku.getId());
                    productSkuAttr.setAttrId(Integer.valueOf(key.toString()));
                    productSkuAttr.setAttrValueId(Integer.valueOf(productSkuReq.get(key).toString()));
                    // TODO: 转换为枚举值
                    productSkuAttr.setFlag(0);
                    attrs.add(productSkuAttr);
                });
            });

            log.info("SKU属性详情: {}", JSONObject.toJSONString(attrs));

            // TODO: 调用MyBatis批量插入SKU和SKU属性
        } catch (Exception e) {
            log.error("saveSku方法发生错误: {}", e.getMessage());
            // 根据应用程序的需求处理异常
        }
    }

    private String getSkuBgImage(ProductSkuReq productSkuReq, List<AttrImageReq> attrImages) {
        String bgImg = null;
        Set set = productSkuReq.keySet();
        Iterator<String> iterator = set.iterator();
        while (iterator.hasNext()) {
            String attrValaueId = iterator.next();
            //根据attrValaueId从attImages中查询到图片地址
            for (AttrImageReq attrImage : attrImages) {
                if (attrImage.getAttrValueId().equals(Integer.valueOf(attrValaueId))) {
                    //获取图片地址
                    bgImg = attrImage.getImageUrl();
                }
            }
        }
        return bgImg;
    }

    //商品详情
    private ProductInfoReq getInfoBySkuId(Long skuId){
        //根据skuid查询到spu基本信息 耗时300ms
        //根据skuid查询规格  耗时1000ms
            //封装规格    耗时700ms
            //封装规格属性 耗时300ms


        return null;
    }

    @Async
    public void checkParmas(ProductInfoReq productInfoReq) {
        //校验类型是否存在
        Integer productTypeId = productInfoReq.getProductTypeId();
        //去数据库查询是否存在
        //int count = maapper.selectCountByType(productTypeId);
        //TODO 待执行sql
        int count =0;
        if (count == 0) {
            log.error("商品类型:{} 不存在",productTypeId);
            throw new ServiceException("商品类型:"+productTypeId+"不存在");
        }
        //货号的唯一性校验
        String productNo = productInfoReq.getProductNo();
        //int count1 = maapper.selectCountByNo(productNo);
        int count1 =0;
        if (count1 > 0) {
            log.error("商品货号:{} 不存在",productNo);
            throw new ServiceException("商品货号:"+productNo+"不存在");
        }
        //校验优惠方式
        Integer offersType = productInfoReq.getOffersType();
        if (offersType == 1) {
            /*//校验会员价格
            ShopMemberReq shopMember = productInfoReq.getShopMember();
            if (shopMember == null) {
                log.error("会员价格不能为空");
                throw new ServiceException("会员价格不能为空");
            }*/
            /*//校验会员价格
            BigDecimal memberPrice = shopMember.getMemberPrice();
            if (memberPrice == null || memberPrice.compareTo(BigDecimal.ZERO) <= 0) {
            }*/
        }


    }
}
